package com.work.work.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work.work.common.R;
import com.work.work.dto.CreateTaskRequest;
import com.work.work.entity.Task;
import com.work.work.service.TaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.lang3.CharSetUtils.count;

@Slf4j
@Tag(name = "任务管理")
@RestController
@RequestMapping("/task")
public class TaskController {
    @Autowired
    private TaskService taskService;

    @Operation(summary = "创建任务")
    @PostMapping("/create")
    public R<Task> create(@RequestBody CreateTaskRequest request) {
        if (request.getTaskName() == null || request.getTaskName().trim().isEmpty()) {
            return R.fail("任务名称不能为空");
        }
        if (request.getProjectId() == null) {
            return R.fail("项目ID不能为空");
        }
        if (request.getPriority() == null) {
            return R.fail("优先级不能为空");
        }

        try {
            // 直接传递 CreateTaskRequest 对象给 service 层
            boolean success = taskService.createTask(request);
            if (success) {
                // 从数据库中获取刚创建的任务
                LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Task::getTaskName, request.getTaskName())
                        .eq(Task::getProjectId, request.getProjectId())
                        .orderByDesc(Task::getId)
                        .last("LIMIT 1");
                Task createdTask = taskService.getOne(queryWrapper);
                return R.ok(createdTask, "任务创建成功");
            }
            return R.fail("创建任务失败");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @Operation(summary = "更新任务")
    @PutMapping("/{id}")
    public R<Boolean> update(@PathVariable Integer id, @RequestBody Task task) {
        task.setId(id);
        return taskService.updateById(task) ? R.ok(true, "项目创建成功") : R.fail("更新任务失败");
    }
@Operation(summary = "删除任务")
@DeleteMapping("/{id}")
public R<Boolean> delete(@PathVariable Integer id) {
    try {
        // 检查任务是否存在
        Task existingTask = taskService.getById(id);
        if (existingTask == null) {
            return R.fail("任务不存在");
        }

        // 删除任务
        boolean success = taskService.removeById(id);
        return success ?
            R.ok(true, "删除成功") :
            R.fail("删除失败");
    } catch (Exception e) {
        log.error("删除任务失败", e);
        return R.fail("删除失败：" + e.getMessage());
    }
}
@Operation(summary = "更新任务")
@PutMapping("/update")
public R<Boolean> update(@RequestBody Task task) {
    // 验证必填字段
    if (task.getId() == null) {
        return R.fail("任务ID不能为空");
    }
    if (task.getTaskName() == null || task.getTaskName().trim().isEmpty()) {
        return R.fail("任务名称不能为空");
    }
    if (task.getProjectId() == null) {
        return R.fail("项目ID不能为空");
    }
    if (task.getPriority() == null) {
        return R.fail("优先级不能为空");
    }
    if (task.getStatus() == null) {
        return R.fail("任务状态不能为空");
    }

    try {
        // 检查任务是否存在
        Task existingTask = taskService.getById(task.getId());
        if (existingTask == null) {
            return R.fail("任务不存在");
        }

        // 更新任务
        boolean success = taskService.updateById(task);
        return success ?
            R.ok(true, "更新成功") :
            R.fail("更新失败");
    } catch (Exception e) {
        log.error("更新任务失败", e);
        return R.fail("更新失败：" + e.getMessage());
    }
}

    @Operation(summary = "获取任务详情")
    @GetMapping("/{id}")
    public R<Task> getById(@PathVariable Integer id) {
        Task task = taskService.getById(id);
        return task != null ? R.ok(task, "项目创建成功") : R.fail("任务不存在");
    }

    @Operation(summary = "分页查询任务")
    @GetMapping("/page")
    public R<Page<Task>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer projectId,
            @RequestParam(required = false) String assignee,
            @RequestParam(required = false) Integer status) {

        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        if (projectId != null) {
            queryWrapper.eq(Task::getProjectId, projectId);
        }
        if (assignee != null) {
            queryWrapper.eq(Task::getAssignee, assignee);
        }
        if (status != null) {
            queryWrapper.eq(Task::getStatus, status);
        }

        return R.ok(taskService.page(new Page<>(current, size), queryWrapper), "项目创建成功");
    }

    @Operation(summary = "根据项目ID查询任务")
    @GetMapping("/project/{projectId}")
    public R<Page<Task>> getTasksByProjectId(
            @PathVariable Integer projectId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return R.ok(taskService.getTasksByProjectId(projectId, current, size), "项目创建成功");
    }

    @Operation(summary = "根据负责人查询任务")
    @GetMapping("/assignee/{assignee}")
    public R<Page<Task>> getTasksByAssignee(
            @PathVariable String assignee,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return R.ok(taskService.getTasksByAssignee(assignee, current, size), "项目创建成功");
    }
    @Operation(summary = "获取任务状态统计")
    @GetMapping("/stats/status")
    public R<Map<String, Object>> getTaskStatusStats() {
        // 统计各状态的数量
        Long notStarted = taskService.count(new LambdaQueryWrapper<Task>()
                .eq(Task::getStatus, 1));
        Long inProgress = taskService.count(new LambdaQueryWrapper<Task>()
                .eq(Task::getStatus, 2));
        Long completed = taskService.count(new LambdaQueryWrapper<Task>()
                .eq(Task::getStatus, 3));
        Long overdue = taskService.count(new LambdaQueryWrapper<Task>()
                .eq(Task::getStatus, 4));

        // 构造echarts所需的数据格式
        Map<String, Object> result = new HashMap<>();

        // X轴数据
        result.put("xAxis", Arrays.asList("未开始", "进行中", "已完成", "已逾期"));

        // Y轴数据
        result.put("series", Arrays.asList(notStarted, inProgress, completed, overdue));

        // 总计数据
        result.put("total", notStarted + inProgress + completed + overdue);

        return R.ok(result, "统计成功");
    }
    @Operation(summary = "更新任务状态")
    @PutMapping("/{taskId}/status/{status}")
    public R<Boolean> updateTaskStatus(
            @PathVariable Integer taskId,
            @PathVariable Integer status) {
        try {
            boolean success = taskService.updateTaskStatus(taskId, status);
            return R.ok(success, "更新成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

}